<!--
 * @Description: 点餐购物车
 * @Author: Kerwin
 * @Date: 2024-07-17 17:25:49
 * @LastEditTime: 2024-10-17 17:07:15
 * @LastEditors:  Please set LastEditors
-->
<template>
    <view>
        <view class="c_container">
            <!-- 列表 -->
            <view class="cart-list" v-if="show">
                <view class="top">
                    <view>已选商品</view>
                    <view @click="clear()">
                        <text class="iconfont hy-icon-delete"></text>
                        清空
                    </view>
                </view>
                <block v-for="(item, index) in cartList" :key="item.id">
                    <view class="cart-item" v-if="item.count > 0">
                        <view class="image-wrapper">
                            <!-- <image class="radio" @click="click_btnSelectedItem(item)" :src="`https://naoyuekang-weixindev.oss-cn-chengdu.aliyuncs.com/newHome/${item.selected ? 'carChecked' : 'carNoChecked'
                            }.png`"></image> -->
                            <image class="image" :src="getImgFullPath(item?.shopProductSku?.productSku?.image)"
                                mode="aspectFill" />
                        </view>
                        <view class="item-right">
                            <text class="title">{{ item.shopProductSku?.product?.name + '（' +
                                item.shopProductSku?.productSku?.name + '）' }}</text>
                            <!-- <text class="attr">{{
                                item.shopProductSku?.productSku?.name
                            }}</text> -->
                            <view class="price red">
                                <view class="money">
                                    <text class="unit l">¥</text>
                                    <text> {{ isMember ? item?.shopProductSku?.memberMoney ?
                                        item?.shopProductSku?.memberMoney : item?.shopProductSku?.money :
                                        item?.shopProductSku?.productSku?.money }} </text>
                                    <!-- <text class="unit r" v-if="item.shopProductSku?.shopProductSkuWalletRules">{{
                                        item.shopProductSku?.shopProductSkuWalletRules[0]
                                            ?.moneyUnit
                                    }}</text> -->
                                </view>
                                <u-number-box class="step" :min="0" disabled-input
                                    :max="item.shopProductSku?.productSku?.count" v-model="item.count" :index="index"
                                    @plus="plus(item)" @minus="minus(item)" size="28"></u-number-box>
                            </view>
                        </view>
                    </view>
                </block>
            </view>
            <view class="actionBar" :class="{ show: count > 0 }">
                <view class="leftBox">
                    <c_ball ref="ballRef">
                        <template #default="{ active }">
                            <view class="car" @click="showList">
                                <image class="pic" :class="{ active }"
                                    src="https://naoyuekang-weixindev.oss-cn-chengdu.aliyuncs.com/newHome/buyCar.png">
                                </image>
                                <!-- <view>购物车</view> -->
                                <view class="num" v-if="count > 0">{{ count }}</view>
                            </view>
                        </template>
                    </c_ball>
                    <view class="total-box">
                        <text class="price">{{ totalMoney ? `¥${totalMoney}` : '' }}</text>
                        <text class="price">{{ realMoney ? `¥${realMoney}` : '' }}</text>
                        <!-- <text class="coupon">
						已优惠
						<text>74.35</text>
						元
					</text> -->
                    </view>
                </view>
                <view class="action-btn-group">

                    <view class="action-btn buyNowBtn" @click="handleBuyNow">去结算</view>
                </view>
            </view>
        </view>
        <view class="mask" :class="{ show: show }" @click="show = false"></view>
    </view>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, ref, watch } from "vue";
import { getImgFullPath } from '@/utils/index'
import { getRect } from "./ballUtill";
import c_ball from "./c_ball.vue"
import { orderApi, productApi } from "@/api";
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store';
import { browserVersion } from "@/utils/common";
import { callIosBridge } from "@/common/JSBridge";

const userStore = useUserStore()
const { accessToken } = storeToRefs(userStore)

const props = defineProps({
    list: {
        type: Array,
        default: () => []
    },
    tabelNumber: {
        type: String,
        default: 0
    },
    isMember: {
        type: Boolean,
        default: false
    },
    isApp: {
        type: Boolean,
        default: false
    }
})

const cartList = computed(() => {
    const list = props.list
    return list
    // return list.reduce((acc, cur) => {
    //     if (cur?.list.length) {
    //         return acc.concat(cur.list.filter((item: { count: number; }) => item.count > 0))
    //     } else {
    //         return acc
    //     }
    // }, [])
})
const count = computed(() => {
    const list = props.list
    const count = list.reduce((acc, cur) => {
        return acc + (cur?.count || 0)
    }, 0)
    // const count = list.reduce((acc, cur) => {
    //     if (cur?.list.length) {
    //         return acc + cur?.list.reduce((acc2: any, cur2: { count: any; }) => {
    //             return acc2 + (cur2.count || 0)
    //         }, 0)
    //     } else {
    //         return acc
    //     }
    // }, 0)
    return count
})

watch(count, (newVal, oldVal) => {
    if (!(newVal > 0)) {
        show.value = false
        return
    }
    calcTotal(cartList.value)
})

const show = ref(false)
function showList() {
    show.value = !show.value
}

const emits = defineEmits(['change', 'clear'])
const plus = (item: { id: number; count: number; }) => {
    const { id, count } = item
    emits('change', {
        name: 'plus',
        id,
        count
    })
}
const minus = (item: { id: number; count: number; }) => {
    const { id, count } = item
    emits('change', {
        name: 'minus',
        id,
        count
    })
}
// 计算总价
const totalMoney = ref(0)
const realMoney = ref(0)
function calcTotal(list: any[]) {
    if (list.length === 0) {
        return
    }
    let totalMoneyTemp = 0
    list.forEach((item: any) => {
        totalMoneyTemp += item.money * item.count
    })
    totalMoney.value = Number(totalMoneyTemp.toFixed(2))
    const orderData = getData()
    const data = getOrderMoney(orderData)
    realMoney.value = data.payMoney
}
function getData() {
    if (!cartList.value || !cartList.value.length) return
    const order = { orderProductSkus: [], status: 0 }
    for (let i = 0; i < cartList.value.length; i += 1) {
        const cartItem = cartList.value[i]
        const { shopProductSku } = cartItem
        // const { shopProductSkus } = cartItem
        // const shopProductSku = shopProductSkus[0]
        if (!shopProductSku) continue
        let shopProductSkuWalletRule = {}
        if (shopProductSku.shopProductSkuWalletRules) {
            shopProductSku.shopProductSkuWalletRules.forEach((item: { uniqueness?: any; }) => {
                if (item.uniqueness) {
                    shopProductSkuWalletRule = item
                }
            })
        }
        const orderProductSku = {
            shopProductSku,
            name: shopProductSku.name,
            skuName: shopProductSku.name,
            skuImage: shopProductSku.productSku.image,
            money: props?.isMember ? shopProductSku.memberMoney ? shopProductSku.memberMoney : shopProductSku.money : shopProductSku.money,
            moneyUnit: shopProductSkuWalletRule.moneyUnit,
            count: cartItem.count,
            shopProductSkuId: shopProductSku.id,
            cartId: cartItem.id,
            status: 0
        }
        order.orderProductSkus.push(orderProductSku)
    }
    if (order.orderProductSkus.length <= 0) {
        uni.showToast({
            icon: 'none',
            title: '请选择商品！'
        })
        return
    }
    return order
}
// 创建订单
async function handleBuyNow() {
    const order = getData()
    const orderData = await getOrderMoney(order)
    await creatOrder(orderData)
}
async function getOrderMoney(orderData: any) {
    const { data } = await orderApi.orderMoney(orderData)
    const { orderMonies, totalMoney, payMoney, money, moneyUnit } = data
    orderData.orderMonies = orderMonies
    orderData.totalMoney = totalMoney
    orderData.payMoney = payMoney
    orderData.money = money
    orderData.moneyUnit = moneyUnit
    return orderData
}
// 创建订单
async function creatOrder(orderData: any) {
    uni.showLoading({ title: '请稍候' })
    orderData.orderExternals = [{
        fieldName: 'restaurantOrderTableNo',
        fieldValue: props.tabelNumber
    }]
    const { data } = await orderApi.orderAdd(orderData).finally(() => {
        uni.hideLoading()
    })
    try {
        productCartDelete()
    } catch (error) {
        console.log(error)
    }
    if (data) {
        const u = browserVersion()
        let scene = '101'
        if (props.isApp) {
            if (u.iPhone) {
                scene = '301'
                window.JSBridge.invoke('goPay', { orderId: data.id, money: data.money })
                // callIosBridge('goPay', { orderId: data.id, money: data.money })
                return
            } else if (u.isAndroid) {
                scene = '201'
                if (window?.Android) {
                    window?.Android?.goPay(data.id, data.money)
                }
                return
            }
        }
        location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}&scene=${scene}`
    }
}

const ballRef = ref<any>()
const context = getCurrentInstance()
const increase = (e: any, ref: any) => {
    if (!ballRef.value) return
    getRect(ref, { context }).then(res => {
        ballRef.value.action({ x: res.left, y: res.top })
    })
    ballRef.value.action(e)
}
defineExpose({
    increase,
    showList
})
async function productCartDelete() {
    uni.showLoading({ title: '请稍候' })
    const ids: any[] = []
    cartList.value.forEach((item: { count: number; }) => {
        item.count = 0
        ids.push(item.id)
    })
    const { code } = await productApi.productCartDelete({
        ids
    }).finally(() => {
        show.value = false
        uni.hideLoading()
    })
    if (code === 200) {
        emits('clear')
    }
}
function clear() {
    uni.showModal({
        content: '确定清空购物车？',
        success: async (e) => {
            if (e.confirm) {
                productCartDelete()
            }
        }
    })
}
</script>
<style lang="scss" scoped>
@import '@/styles/helper.scss';

.c_container {
    position: fixed;
    left: 5%;
    bottom: calc(130rpx + env(safe-area-inset-bottom));
    width: 90%;
    z-index: 99;

    /* 购物车列表项 */
    .cart-list {
        padding-bottom: 40rpx;
        max-height: 900rpx;
        overflow-y: scroll;

        .top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 30rpx;
            position: sticky;
            top: 0;
            z-index: 10;
            background: #fff;
        }

        position: absolute;
        left: 0;
        bottom: 38rpx;
        background: #fff;
        width: 100%;
        border-radius: 20rpx 20rpx 0 0;

        .cart-item {
            display: flex;
            position: relative;
            padding: 20rpx 20rpx;
            background-color: #fff;
            border-radius: 10rpx;
            align-items: center;

            .image-wrapper {
                flex-shrink: 0;
                position: relative;

                .radio {
                    display: block;
                    width: 42rpx;
                    height: 42rpx;
                    position: absolute;
                    left: 0;
                    top: 50%;
                    margin-top: -22rpx;
                }

                .image {
                    border-radius: 8rpx;
                    width: 120rpx;
                    height: 120rpx;
                }
            }

            .checkbox {
                position: absolute;
                left: -16rpx;
                top: -16rpx;
                z-index: 8;
                font-size: 44rpx;
                line-height: 1;
                padding: 4rpx;
                color: $uni-text-color-disable;
                background: #fff;
                border-radius: 50px;
            }

            .item-right {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;
                position: relative;
                padding-left: 20rpx;

                .title {
                    font-size: $uni-font-size-base + 2rpx;
                    color: $uni-text-color-dark;
                    line-height: 40rpx;
                }

                .price {
                    font-size: $uni-font-size-base + 2rpx;
                    color: $uni-text-color-dark;
                    font-weight: bold;
                    margin-top: 10rpx;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .money {
                        flex-shrink: 0;
                    }

                    .unit {
                        font-weight: normal;
                        flex-shrink: 0;
                        font-size: 22rpx;

                        &.r {
                            margin-left: 8rpx;
                        }
                    }

                    .step {
                        margin-left: 20rpx;
                    }
                }

                .red {
                    color: red;
                }

                .attr {
                    font-size: $uni-font-size-sm + 2rpx;
                    color: $uni-text-color-light;
                    margin-top: 10rpx;
                    @include ellipsis(2);
                }
            }

            .hy-icon-delete {
                font-size: 36rpx;
                align-self: start;
            }
        }
    }

    .actionBar {

        z-index: 95;
        display: flex;
        justify-content: space-between;
        align-items: center;
        opacity: 0;
        width: 60%;
        // padding: 10rpx 30rpx;
        // padding-bottom: calc(10rpx + env(safe-area-inset-bottom));
        box-sizing: border-box;
        background: #fff;
        border-radius: 100rpx;
        box-shadow: 0 0 6rpx 0 rgba(0, 0, 0, 0.1);
        transform: translateX(0);

        &.show {
            opacity: 1;
            transform: translateX(0);
            transition: all 0.3s ease;
            width: 100%;
        }

        .leftBox {
            display: flex;
            justify-content: space-between;
            align-content: center;
            gap: 20rpx;
            margin: 16rpx 0 0 20rpx;

            .car {
                width: 70rpx;
                position: relative;
                font-size: 22rpx;
                color: #242526;
                text-align: center;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;

                .pic {
                    display: block;
                    margin: 0 auto;
                    width: 48rpx;
                    height: 48rpx;
                    margin-bottom: 6rpx;
                    transition: transform 0.3s ease;

                    &.active {
                        transform: scale(1.5);
                    }
                }

                .num {
                    width: 34rpx;
                    height: 34rpx;
                    text-align: center;
                    line-height: 36rpx;
                    font-size: 20rpx;
                    color: #fff;
                    position: absolute;
                    top: -14rpx;
                    right: -6rpx;
                    border-radius: 50%;
                    background-color: #f74e3f;
                }
            }

            .p-b-btn {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                font-size: 22rpx;
                color: #242526;
                // width: 100rpx;
                height: 100rpx;
                text-align: center;

                .pic {
                    display: block;
                    margin: 0 auto;
                    width: 40rpx;
                    height: 40rpx;
                    margin-bottom: 6rpx;
                }

                &.active {
                    color: #f75931;
                }
            }

            .total-box {
                .price {
                    font-size: 28rpx;
                    color: #f74e3f;
                    font-weight: bold;
                    margin-left: 20rpx;
                }
            }
        }

        .action-btn-group {
            display: flex;
            width: 400rpx;
            height: 76rpx;
            overflow: hidden;
            position: relative;
            justify-content: flex-end;

            .action-btn {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 200rpx;
                height: 76rpx;
                line-height: 76rpx;
                font-size: 30rpx;
                color: #fff;
                padding: 0;
                border-radius: 0;

                &.single {
                    width: 100%;
                    border-radius: 78rpx !important;

                }
            }

            .buyNowBtn {
                background-color: #f74e3f;
                // border-radius: 78rpx;
                border-radius: 0 100rpx 100rpx 0;
                color: #fff;
            }

            .carBtn {
                background-color: #fee7de;
                border-radius: 100rpx 0 0 100rpx;
                color: #f74e3f;
            }
        }
    }
}

.mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 90;
    display: none;

    &.show {
        display: block;
    }
}
</style>